<template>
  <a-row :gutter="24">
    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-directory-tree
          v-if="treeList.length"
          :showIcon="false"
          :treeData="treeList"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields"
          style="overflow: unset" />
      </a-card>
    </a-col>

    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item label="网关名称">
                  <a-select style="width: 100%" v-model="queryParam.gatewayId" allow-clear placeholder="请选择网关名称">
                    <a-select-option v-for="(item, ind) in gatewayList" :key="ind" :value="item.id">{{ item.gatewayName
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="(!advanced && 8) || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="padding-left: 16px;">
                  <a-button type="primary" class="btn_search_reset" @click="$refs.table.refresh(true)"><a-icon
                    type="search" />查询</a-button>
                </span>
              </a-col>
              <a-col :md="(!advanced && 8) || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="float: right;">
                  <a-button class="btn_add" type="primary" @click="hanldAdd(stationId)" icon="plus">新增</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowKey="(record) => record.id">
          <span slot="taskType" slot-scope="text">
            {{ taskTypeFilter(text) }}
          </span>

          <span slot="taskStatus" slot-scope="text">
            {{ taskStatusFilter(text) }}
          </span>
        </s-table>
        <add-form ref="addForm" @ok="handleOk" :addTitle="addTitle" />
        <edit-form ref="editForm" @ok="handleOk" />
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import { STable } from '@/components'
import { page, del } from '@/api/modular/main/gatewayfirmware/gatewayfirmware'
import addForm from './addForm'
import editForm from './editForm'
import { Empty } from 'ant-design-vue'
import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
import moment from 'moment'
import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'
import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'

export default {
  components: {
    STable,
    addForm,
    editForm
  },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      gatewayList: [],
      gatewayTaskStatusList: [],
      gatewayTaskTypeList: [],
      queryParam: {
        stationId: 0
      }, // 查询参数
      columns: [
        // 表头
        {
          title: '固件名称',
          dataIndex: 'firmwareName'
        },
        {
          title: '版本名称',
          dataIndex: 'versionName'
        },
        {
          title: '版本号',
          dataIndex: 'versionNumber'
        },
        {
          title: '更新说明',
          dataIndex: 'updateRemark'
        },
        {
          title: '创建日期',
          dataIndex: 'createTime',
          width: 150,
          align: 'center'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      treeList: [],
      addTitle: '',
      gatewayLoading: true,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id'
      },
      treeLoading: true,
      stationId: '',
      btnLoading: false
    }
  },
  created () {
    this.getStationTree()
    this.getGatewayTaskStatusList()
    this.getGatewayTaskTypeList()
  },
  methods: {
    hanldAdd (stationId) {
      if (stationId === '') {
        this.$message.error('请选择站点')
        return
      }
      this.$refs.addForm.add(stationId)
    },
    taskTypeFilter (record) {
      let str = ''
      this.gatewayTaskTypeList.forEach((item) => {
        if (record === item.code) {
          str = item.value
        }
      })
      return str
    },
    taskStatusFilter (record) {
      let str = ''
      this.gatewayTaskStatusList.forEach((item) => {
        if (record === item.code) {
          str = item.value
        }
      })
      return str
    },
    getGatewayTaskStatusList () {
      sysDictTypeDropDown({ code: 'gateway_task_status' }).then((res) => {
        if (res.success) {
          this.gatewayTaskStatusList = res.data
        }
      })
    },
    getGatewayTaskTypeList () {
      sysDictTypeDropDown({ code: 'gateway_task_type' }).then((res) => {
        if (res.success) {
          this.gatewayTaskTypeList = res.data
        }
      })
    },
    getGatewayList (stationId) {
      gatewayList({ stationId: stationId }).then((res) => {
        if (res.success) {
          this.gatewayList = res.data
          this.gatewayIds = []
          this.gatewayList.filter((value) => {
            this.gatewayIds.push(value.id)
          })
          this.queryParam.gatewayIds = this.gatewayIds.toString()
          this.handleOk()
        }
      })
    },
    del (record) {
      record.createdAt = moment(record.createdAt).format('YYYY-MM-DD HH:mm:ss')
      del(record)
        .then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    getStationTree () {
      treeList(Object.assign(this.queryParam)).then((res) => {
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.treeList = res.data
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleClick (e) {
      var returnedItem = ''

      this.treeList.forEach((item) => {
        if (item.id == e[0]) {
          returnedItem = item
          return item
        } else if (item.children.length > 0) {
          if (item.children.id = e[0]) {
            returnedItem = item.children
            return item.children
          }
        }
      })

      returnedItem.forEach((item) => {
        if (item.id == returnedItem.id) {
          this.addTitle = item.title
        }
      })

      if (e.length > 0) {
        this.queryParam = {}
        this.stationId = e.toString()
        this.queryParam.stationId = e.toString()
        this.getGatewayList(e.toString())
      } else {
        this.queryParam.gatewayIds = ''
        this.handleOk()
      }
    },
    isShow () {
      if (this.stationId) {
        return true
      }
      return false
    }
  }
}
</script>
<style lang="less" scoped>
/*@import '../~@/assets/css/list.less';*/
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}

.ant-tree li {
  overflow: no-content !important;
  white-space: pre-wrap !important;
}
.table-page-search-wrapper{
  padding: 0 10px;
  /deep/ .ant-row{
    margin-left: 0px !important;
  }
}
</style>
